package com.xcode.xandrdb.translator;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import com.xcode.xandrdb.annotation.Table;

/**
 * 注解Table的解析器
 * 
 * @author 肖蕾
 */
public class TableTranslator
{
	private Class<?> clazz;
	private Field fields[];
	private Method methods[];

	public TableTranslator(Object object)
	{
		clazz = object.getClass();
		fields = clazz.getDeclaredFields();
		methods = clazz.getDeclaredMethods();
	}
	public TableTranslator(Class<?> T)
	{
		clazz = T;
		fields = clazz.getDeclaredFields();
		methods = clazz.getDeclaredMethods();
	}

	/**
	 * 获取建表的SQL语句
	 * 
	 * @return
	 */
	public String getCreateSql()
	{
		String sql = "CREATE TABLE ";
		String tabName = "";
		if (clazz.isAnnotationPresent(Table.class))
		{
			Table table = clazz.getAnnotation(Table.class);
			tabName = table.value();
		}
		tabName = ("".equals(tabName) ? clazz.getSimpleName() : tabName);
		sql += "'" + tabName + "' (";
		for (int i = 0; i < fields.length; i++)
		{
			Field field = fields[i];
			// 类型
			String type = getFieldSqlType(field);
			// 主键
			boolean PRIMARY_KEY = field.isAnnotationPresent(Table.PRIMARY_KEY.class);
			// 自增长
			boolean AUTOINCREMENT = field.isAnnotationPresent(Table.AUTOINCREMENT.class);
			// 不为空
			boolean NOT_NULL = field.isAnnotationPresent(Table.NOT_NULL.class);
			if (i == 0)
			{
				sql += "'" + field.getName() + "' " + type + (PRIMARY_KEY ? " PRIMARY KEY" : "")
						+ (AUTOINCREMENT ? " AUTOINCREMENT" : "") + (NOT_NULL ? " NOT NULL" : "");
			} else
			{
				sql += ",'" + field.getName() + "' " + type + (PRIMARY_KEY ? " PRIMARY KEY" : "")
						+ (AUTOINCREMENT ? " AUTOINCREMENT" : "") + (NOT_NULL ? " NOT NULL" : "");
			}
		}
		sql += ");";
		return sql;
	}

	private String getFieldSqlType(Field field)
	{
		String type = "TEXT";
		if (field.isAnnotationPresent(Table.Type.INTEGER.class) || field.getType() == Integer.class
				|| field.getType() == int.class)
		{
			type = "INTEGER";
		} else
		{
			type = "TEXT";
		}
		return type;
	}

}
